package weifei.live.simulation.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import weifei.live.simulation.entity.TradeArea;
import weifei.live.simulation.entity.TradeAreaGroup;
import weifei.web.Result;


@RestController
@RequestMapping("/tradeArea")
public class TradeAreaController
{
    @Autowired
    private TradeArea dao_trade_area;
    @Autowired
    private TradeAreaGroup dao_trade_area_group;

    @GetMapping("/searchTradeAreaByName")
    @PostMapping("/searchTradeAreaByName")
    public Result searchTradeAreaByName(@RequestParam("name") String searchName)
    {
        QueryWrapper<TradeArea> qw_trade_area = new QueryWrapper<>();
        qw_trade_area.like(TradeArea.Column.Name.getName(), searchName);
        var list = this.dao_trade_area.selectList(qw_trade_area);
        return Result.success("搜索成功", list);
    }


    /**
     * 获取 60km 距离左右的 商圈
     * 差 0.5 经纬度
     * */
    @GetMapping("/getNearTradeAreaList")
    @PostMapping("/getNearTradeAreaList")
    public Result getNearTradeAreaList(
            @RequestParam("longitude") Double longitude,
            @RequestParam("latitude") Double latitude
        )
    {
        if (longitude == null || latitude == null)
            return Result.exception("参数错误");

        QueryWrapper<TradeArea> qw_trade_area = new QueryWrapper<>();
        qw_trade_area.ge(TradeArea.Column.Longitude.getName(), longitude - 0.5);
        qw_trade_area.le(TradeArea.Column.Longitude.getName(), longitude + 0.5);
        qw_trade_area.ge(TradeArea.Column.Latitude.getName(), latitude - 0.5);
        qw_trade_area.le(TradeArea.Column.Latitude.getName(), latitude + 0.5);
        var list = this.dao_trade_area.selectList(qw_trade_area);
        return Result.success("获取成功", list);
    }



    @GetMapping("/getGroupIDsByTradeAreaID")
    @PostMapping("/getGroupIDsByTradeAreaID")
    public Result getGroupIDsByTradeAreaID(@RequestParam("id") Integer tradeAreaId)
    {
        if (tradeAreaId == null)
            return Result.exception("参数错误");

        var ta = new TradeArea(tradeAreaId).selectById();
        if (ta == null)
            return Result.failed("商圈不存在");

        QueryWrapper<TradeAreaGroup> qw_trade_area_group = new QueryWrapper<>();
        qw_trade_area_group.eq(TradeAreaGroup.Column.TradeAreaID.getName(), tradeAreaId);
        var list = this.dao_trade_area_group.selectList(qw_trade_area_group);
        var ids = new Integer[list.size()];
        for (var i = 0; i < list.size(); i++)
            ids[i] = list.get(i).getGroupId();
        return Result.success("获取成功", ids);
    }
}


